April 15, 2021
가중치를 가지는 트리에서 임의의 두 노드를 선택합니다. 이 때 두 노드를 연결하는 가중치들의 합이 최대가 되는 가중치를 반환하세요.(지름 반환 문제)
어느 노드에서라도 가중치들의 합이 최대가 되는 노드를 찾으면 그 노드는 지름이 되는 두 노드 중에 한 노드가 된다.
결론적으로, dfs로 모든 노드를 순회한다. 노드를 거쳐갈 때 마다 가중치를 기록해 최대값을 갱신하면 정답을 구할 수 있다.
burglary image by Programmers
그래프를 구성하는 vertex를 class로 선언한다. adj_list는 vertex에 연결된 vertices들의 index와 weight를 저장한다.
class Vertex:
def __init__(self, adj_vertex = None):
if adj_vertex:
self.adj_list = [adj_vertex] # [(index, weight)]
else:
self.adj_list = []다음으로 vertex들을 관리할 그래프를 클래스를 선언하고, vertex들을 관리할 vertices를 선언한다.
class Graph:
def __init__(self, n):
# 인접행렬 보다 리스트가 유리(트리기 때문에)
self.vertices = [0] * (n + 1)주어진 정보(vertex )
def insert(self, v_index, adj_v_index, weight):
if self.vertices[v_index] == 0:
self.vertices[v_index] = Vertex((adj_v_index, weight))
else:
self.vertices[v_index].adj_list.append((adj_v_index, weight))
if self.vertices[adj_v_index] == 0:
self.vertices[adj_v_index] = Vertex((v_index, weight))
else:
self.vertices[adj_v_index].adj_list.append((v_index, weight))